package cc.eguid.tools.utils;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;

/**
 * 图像压缩，1.0版本，后续需要继续优化
 */
public class ImageCompress {
    /**
     * 压缩BufferedImage并返回压缩后的BufferedImage
     *
     * @param originalImage 原始图片
     * @param quality       压缩质量 (0.0-1.0)
     * @return 压缩后的BufferedImage
     */
    public static BufferedImage compressBufferedImage(BufferedImage originalImage, float quality) throws IOException {
        if (quality < 0.0f || quality > 1.0f) {
            throw new IllegalArgumentException("压缩质量必须在0.0到1.0之间");
        }

        // 使用内存缓冲进行JPEG压缩
        ByteArrayOutputStream compressedStream = new ByteArrayOutputStream();

        // 获取JPEG编码器
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg");
        if (!writers.hasNext()) {
            throw new IOException("没有找到JPEG编码器");
        }

        ImageWriter writer = writers.next();
        ImageWriteParam param = writer.getDefaultWriteParam();

        // 设置压缩参数
        // param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality);

        // 压缩到内存
        writer.setOutput(ImageIO.createImageOutputStream(compressedStream));
        writer.write(null, new IIOImage(originalImage, null, null), param);
        writer.dispose();

        // 从内存读取回BufferedImage
        ByteArrayInputStream inputStream = new ByteArrayInputStream(compressedStream.toByteArray());
        BufferedImage compressedImage = ImageIO.read(inputStream);

        return compressedImage;
    }
}
